package com.google.appengine.echogear.jobs;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Logger;

import com.google.appengine.echogear.core.EchoJob;

public final class SinaWeiboJob extends EchoJob {

	private static final long serialVersionUID = -6022916155938171815L;
	
	private static final Logger log = Logger.getLogger(SinaWeiboJob.class.getName());

	public SinaWeiboJob() {
		super();
	}

	@Override
	public boolean init() {
		return true;
	}

	@Override
	public boolean send(String messgae) {
		try {
			
			
			String[] param = this.getParam().split(",");
			URL url = new URL("https://api.weibo.com/2/statuses/update.json");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);

			StringBuffer params = new StringBuffer();
			params.append("access_token").append("=").append(param[0])
					.append("&").append("status").append("=").append(URLEncoder.encode(messgae, "utf-8"));
			byte[] bypes = params.toString().getBytes();
			connection.getOutputStream().write(bypes);
			InputStream inStream = connection.getInputStream();
			System.out.println(new String(readInputStream(inStream), "utf-8"));
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}

}
